from django.template.defaultfilters import slugify as djslugify

def slugify(obj, fieldname_to_slugify, fieldname_of_slug):
    """Create a slug which does not collide with other slugs for
       objects of this type.
       Pass an object (not a class), the name of the field to slugify,
       and the name of the field that this object type stores slugs in
       (to check for collisions).
    """
    addition = ""
    addition_count = 0
    slug_exists = True
    obj_type = obj.__class__
    value_to_slugify = getattr(obj, fieldname_to_slugify)
    DNE = getattr(obj_type, "DoesNotExist")
    while slug_exists:
        potential_slug = djslugify(value_to_slugify) + addition
        try:
            match = obj_type.objects.get(**{fieldname_of_slug: potential_slug})
        except DNE:
            # this slug doesn't exist; return it
            slug_exists = False
            return potential_slug
        # This slug does exist
        # If it's our slug, that's OK; return it
        if match.id == obj.id:
            return potential_slug
        # It isn't ours, so add one to addition and go round again
        addition_count += 1
        addition = "_%s" % addition_count

